﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IBusiness_impl
{
    /// <summary>
    /// 用户，业务处理
    /// </summary>
    public sealed class UserBusiness : BaseBusiness
    {
        readonly ILogin_userDAL login_UserDAL = ServicesHelpter.GetService<ILogin_userDAL>();
        readonly ILogin_logDAL  login_LogDAL = ServicesHelpter.GetService<ILogin_logDAL>();


        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        /// 创建时间：2022-11-24 09:20:25。作者：王浩力
        public IResult CheckLogin(string account, string password)
        {
#if DEBUG
            //////////测试；超级管理员
            account = "admin";
            password = "Km7756@gts";
#else

#endif

            if (string.IsNullOrWhiteSpace(account))
            {
                return new Result("请输入账号");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                return new Result("请输入密码");
            }
            var result = login_UserDAL.GetLoginUser(account);
            if (result.Code != 200)
            {
                //记录登录日志
                login_LogDAL.AddLoginLog(result.Data, 0, result.Msg);
                return new Result(result.Msg);
            }
            if (result.Data == null)
            {
                //记录登录日志
                login_LogDAL.AddLoginLog(result.Data, 0, "用户没找到");
                return new Result("用户没找到");
            }
            if (result.Data.U_stat == 0)
            {
                //记录登录日志
                login_LogDAL.AddLoginLog(result.Data, 0, "用户被禁用");
                return new Result("用户被禁用");
            }

            //检查密码
            string checkHash = HashEncrypt.SHA256Encrypt(password + result.Data.Password_salt);
            if (!result.Data.Password_hash.Equals(checkHash))
            {
                //记录登录日志
                login_LogDAL.AddLoginLog(result.Data,0, "密码错误");
                return new Result("密码错误");
            }

            //登录成功，将用户信息记缓存
            System.Runtime.Caching.MemoryCache.Default.Set(CommonConfig.LoginUserCacheKey, result.Data, new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromHours(480) });

            //记录登录日志
            login_LogDAL.AddLoginLog(result.Data,1,"登录成功");

            return new ResultSuccess("登录成功");
        }

        /// <summary>
        /// 创建用户,密码存入E3
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// 创建时间：2022-11-24 13:41:31。作者：王浩力
        public Result AddUser(Login_user user)
        {
            if (user == null)
            {
                return new Result("user不可为空");
            }
            if (string.IsNullOrWhiteSpace(user.User_account))
            {
                return new Result("账号不可为空");
            }

            //注释时间：2022-12-6 17:32:23。
            //if (string.IsNullOrWhiteSpace(user.User_real_name))
            //{
            //    return new Result("姓名不可为空");
            //}
            //if (string.IsNullOrWhiteSpace(user.E3))
            //{
            //    return new Result("密码不可为空");
            //}
            Snowflake snowflake = new Snowflake(1, 1);
            user.Id = snowflake.NextId();
            user.E3 = "km741852@";
            user.Password_salt = DateTime.Now.Ticks.ToString();
            user.Password_hash = HashEncrypt.SHA256Encrypt(user.E3 + user.Password_salt);

            var result = login_UserDAL.AddUser(user);
            return result;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        /// 创建时间：2022-12-3 18:56:58。作者：王浩力
        public List<Login_user> GetAllUser()
        {
            return login_UserDAL.GetAll_LoginUser();
        }

        /// <summary>
        /// 修改指定列数据；如果是账号需要验证是否重复
        /// </summary>
        /// <param name="columnName">列名</param>
        /// <param name="columnValue">列值</param>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        /// 创建时间：2022-12-5 15:48:51。作者：王浩力
        public IResult Update(string columnName, object columnValue, long id)
        {
            var result = login_UserDAL.GetLoginUserById(id);
            if (result.Code != 200)
            {
                return new Result(result.Msg);
            }
            if (result.Data == null)
            {
                return new Result("没有找到要修改的记录");
            }

            //检查账号是否重复。//添加时间：2022-12-6 13:55:43
            if (string.Equals(columnName, "User_account", StringComparison.OrdinalIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(columnValue.ToString()))
                {
                    return new Result("账号不可为空");
                }
                if (!string.Equals(result.Data.User_account, columnValue.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    //检查账号是否存在
                    var resultCheck = login_UserDAL.GetLoginUser(columnValue.ToString());
                    if (resultCheck.Code == 200 && resultCheck.Data != null && resultCheck.Data.Id > 0)
                    {
                        return new Result("账号已存在，请另设");
                    }
                }
            }
            return login_UserDAL.UpdateColumn(id, columnName, columnValue);
        }

    }

}
